package com.example.springboot.config.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.retry.RetryUntilElapsed;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * zookeeper的配置类
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/24 14:21
 */
@Configuration
public class ZookeeperConfig {
    @Value("${zookeeper.address}")
    private String zookeeperAddresses;
    /**
     * 注入curator的客户端
     *
     * @return
     */
    @Bean
    public CuratorFramework curatorFramework() {
        // 重连策略
        // 重连一次
        RetryPolicy retryPolicy = new RetryOneTime(3000);
        // 指定重连次数
        RetryPolicy retryPolicy1 = new RetryNTimes(3, 3000);
        // 每三秒重连一次，总等待超过十秒后停止重连
        RetryPolicy retryPolicy2 = new RetryUntilElapsed(10000, 3000);
        // 随着重连次数的增加，重连的间隔也会增加
        // 算法
        RetryPolicy retryPolicy3 = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                // ip端口号
                .connectString(zookeeperAddresses)
                // 会话超时时间
                .sessionTimeoutMs(5000)
                // 链接断开后的会话重试
                .retryPolicy(new RetryOneTime(3000))
                // 命名空间，父节点
                .namespace("create")
                .build();
        return client;
    }
}
